---
title: "Example: Hybrid Vector Search | RAG | Kastrax Docs"
description: Example of using metadata filters with PGVector to enhance vector search results in Kastrax.
---

import { GithubLink } from "@/components/github-link";

# Hybrid Vector Search ✅

When you combine vector similarity search with metadata filters, you can create a hybrid search that is more precise and efficient.
This approach combines:

- Vector similarity search to find the most relevant documents
- Metadata filters to refine the search results based on additional criteria

This example demonstrates how to use hybrid vector search with Kastrax and PGVector.

## Overview ✅

The system implements filtered vector search using Kastrax and PGVector. Here's what it does:

1. Queries existing embeddings in PGVector with metadata filters
2. Shows how to filter by different metadata fields
3. Demonstrates combining vector similarity with metadata filtering

> **Note**: For examples of how to extract metadata from your documents, see the [Metadata Extraction](../embedding/metadata-extraction.mdx) guide.
> 
> To learn how to create and store embeddings, see the [Upsert Embeddings](/examples/rag/upsert/upsert-embeddings) guide.

## Setup ✅

### Environment Setup

Make sure to set up your environment variables:

```bash filename=".env"
OPENAI_API_KEY=your_openai_api_key_here
POSTGRES_CONNECTION_STRING=your_connection_string_here
```

### Dependencies

Import the necessary dependencies:

```typescript copy showLineNumbers filename="src/index.ts"
import { embed } from 'ai';
import { PgVector } from '@kastrax/pg';
import { openai } from '@ai-sdk/openai';
```

## Vector Store Initialization ✅

Initialize PgVector with your connection string:

```typescript copy showLineNumbers{4} filename="src/index.ts"
const pgVector = new PgVector(process.env.POSTGRES_CONNECTION_STRING!);
```

## Example Usage ✅

### Filter by Metadata Value

```typescript copy showLineNumbers{6} filename="src/index.ts"
// Create embedding for the query
const { embedding } = await embed({
  model: openai.embedding('text-embedding-3-small'),
  value: '[Insert query based on document here]',
});

// Query with metadata filter
const result = await pgVector.query({
  indexName: 'embeddings',
  queryVector: embedding,
  topK: 3,
  filter: {
    'path.to.metadata': {
      $eq: 'value',
    },
  },
});

console.log('Results:', result);
```

<br />
<br />
<hr className="dark:border-[#404040] border-gray-300" />
<br />
<br />
<GithubLink
  link={
    "https://github.com/kastrax-ai/kastrax/blob/main/examples/basics/rag/hybrid-vector-search"
  }
/>
